#
#===============================================================================
#
#         FILE:  Seen.pm
#
#  DESCRIPTION:  Track seen data based on channel
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/20/2010 06:06:11 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::Seen;

use Convert::Age;

sub register {
    my $self = shift;
    my $dbh = shift;

    my $sth = $dbh->prepare("SELECT * FROM sqlite_master WHERE type='table' AND name=?");
    $sth->bind_param(1, 'seen');
    $sth->execute;

    my $test = $sth->fetch; # rows has nothing unless you do a fetch.
    if( ! $sth->rows ) {
        $dbh->do("CREATE TABLE seen (id integer primary key autoincrement, nick varchar, channel varchar, 
		host varchar, details varchar, event varchar,
                create_date timestamp DEFAULT CURRENT_TIMESTAMP, 
                last_update timestamp);");
        $dbh->do("CREATE UNIQUE INDEX channel_seen ON seen (nick, channel)");
    }

    return ('cmd' => 'seen', 'pat' => '^!seen\s+(.+)', 'events' =>
		    {'irc_join'=>'seen_data',
		    'irc_part'=>'seen_data',
		    'irc_quit'=>'seen_data',
		    'irc_kick'=>'seen_data',
		    'irc_nick'=>'seen_data',} );
}

sub help {
    my $self = shift;
    
    return ('Shows when a nick was last seen in the channel');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    my $dbh = $conf{'dbh'};

    if( $target !~ /^#/ ) { return; } # we only track channel seen data

    $nickhost =~ /(.*)!(.*)@(.*)/;
    my ($nick, $ident, $host) = ($1, $2, $3);

    $msgtxt =~ /^!seen\s+(.+)/;
    my $seennick = $1;

    my $sth = $dbh->prepare("SELECT *, strftime('\%s', 'now') - strftime('\%s', last_update) AS age FROM seen WHERE lower(channel)=lower(?) AND lower(nick)=lower(?)");
    $sth->bind_param(1, $target);
    $sth->bind_param(2, $seennick);
    $sth->execute;

    my $row = $sth->fetchrow_hashref;
    if( $sth->rows ) {
	my $msg;
	if( $row->{'event'} eq 'join' ) {
	    $msg = sprintf('%s (%s) joined %s %s ago', 
			    $seennick, $row->{'host'}, $target,
			    Convert::Age::encode($row->{'age'}));
	}
	elsif( $row->{'event'} eq 'quit' ) {
	    $msg = sprintf('%s (%s) quit %s ago with reason: %s',
			    $seennick, $row->{'host'},
			    Convert::Age::encode($row->{'age'}),
			    $row->{'details'});
	}
	elsif( $row->{'event'} eq 'nick' ) {
	    $msg = sprintf('%s (%s) changed nick to %s %s ago',
			    $seennick, $row->{'host'}, $row->{'details'},
			    Convert::Age::encode($row->{'age'}));
	}
	elsif( $row->{'event'} eq 'part' ) {
	    $msg = sprintf('%s (%s) parted %s %s ago'.($row->{'details'}?' with reason: %s':''),
			    $seennick, $row->{'host'}, $target,
			    Convert::Age::encode($row->{'age'}),
			    ($row->{'details'}?($row->{'details'}):()));
	}
	elsif( $row->{'event'} eq 'kick' ) {
	    $msg = sprintf('%s (%s) '.$row->{'details'},
			    $seennick, $row->{'host'}, 
			    Convert::Age::encode($row->{'age'}));
	}

	$kernel->post($sender => privmsg => $target => $msg);
    }
    else {
	$kernel->post($sender => privmsg => $target => sprintf('%s has not been seen here.', $seennick));
    }
}

sub seen_data {
    my $self = shift;
    my ($kernel, $sender, $event, $args, %conf) = @_;
    my $dbh = $conf{'dbh'};

    my $nickhost = $args->[0];
    $nickhost =~ /(.*)!(.*)@(.*)/;
    my ($nick, $ident, $host) = ($1, $2, $3);
    my $channel;

    my $details;
    if( $event eq 'irc_join' ) {
	$details = '';
	$channel = $args->[1];
    }
    elsif( $event eq 'irc_nick' ) {
	$details = $args->[1];
	$channel = undef;
    }
    elsif( $event eq 'irc_part' ) {
	$details = $args->[2];
	$channel = $args->[1];
    }
    elsif( $event eq 'irc_kick' ) {
	$details = 'was kicked from '.$args->[1].' by '.$nick.' %s ago with reason: '.$args->[3];
	$nick = $args->[2];
	$nickhost = $nick;
	$channel = $args->[1];
    }
    elsif( $event eq 'irc_quit' ) {
	$details = $args->[1];
	$channel = undef;
    }
    $event =~ s/^irc_//;

    if( $channel ) {
	my $sth = $dbh->prepare("SELECT * FROM seen WHERE nick=? AND channel=?");
	$sth->bind_param(1, $nick);
	$sth->bind_param(2, $channel);
	$sth->execute;

	my $row = $sth->fetchrow_hashref;
	if( $sth->rows ) {
	    $sth = $dbh->prepare("UPDATE seen SET last_update=current_timestamp, host=?, details=?, event=?  WHERE id=?");
	    $sth->bind_param(1, $nickhost);
	    $sth->bind_param(2, $details);
	    $sth->bind_param(3, $event);
	    $sth->bind_param(4, $row->{'id'});
	    $sth->execute;
	}
	else {
	    $sth = $dbh->prepare("INSERT INTO seen (nick, channel, host, details, event, last_update) VALUES (?,?,?,?,?,current_timestamp);");
	    $sth->bind_param(1, $nick);
	    $sth->bind_param(2, $channel);
	    $sth->bind_param(3, $nickhost);
	    $sth->bind_param(4, $details);
	    $sth->bind_param(5, $event);
	    $sth->execute;
	}
    }
    else {
	my $sth = $dbh->prepare("UPDATE seen SET last_update=current_timestamp, host=?, details=?, event=? WHERE nick=?");
	$sth->bind_param(1, $nickhost);
	$sth->bind_param(2, $details);
	$sth->bind_param(3, $event);
	$sth->bind_param(4, $nick);
	$sth->execute;
    }
}

1;
